Next.jsのAPI Routes
pages/api/配下にコードを置くとAPI Endpointになる
例
code:pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'
type Response = {
name: string
}
export default (req: NextApiRequest, res: NextApiResponse<Response>) => {
res.status(200).json({ name: 'John Doe' })
}
code:client.ts
const { data, error } = useSWR('/api/hello', fetcher)
型付け
これで良いと思うmrsekut.icon
typeraと同じことをZod & Next.jsでやっている感じ code:ts
import { NextApiRequest, NextApiResponse } from "next";
import { z, ZodSchema } from "zod";
export function withZod<T extends ZodSchema>(
schema: T,
next: (
req: Omit<NextApiRequest, "query" | "body"> & z.infer<T>,
res: NextApiResponse
) => unknown | Promise<unknown>
) {
return async (req: NextApiRequest, res: NextApiResponse) => {
const parsed = schema.safeParse(req);
if (!parsed.success) {
res.status(400).json({
message: "Bad Request",
issues: JSON.parse(parsed.error.message),
});
return;
}
return next(req, res);
};
}
code:使用する.ts
import { withZod } from "@/lib/next/withZod";
import { NextApiHandler } from "next";
import { z } from "zod";
const handleGet = withZod(
z.object({
query: z.object({ name: z.string() }),
}),
async (req, res) => {
const name = req.query.name; // const name: string
res.status(200).json({ message: Hello ${name} });
}
);
const handler: NextApiHandler = async (req, res) => {
switch (req.method) {
case "GET":
return handleGet(req, res);
default:
res.status(405).json({ message: "Method Not Allowed" });
return;
}
};
export default handler;
記事中のrefine使っている箇所は流石にだるいので何かしら工夫できそう